package com.wutong.erb.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.List;

/**
 * 全局跨域配置
 * @author wutong
 */
@Configuration
public class CorsConfig {
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();

        // 允许的源（生产环境建议配置具体域名）
        //TODO: 生产环境建议配置具体域名
        config.setAllowedOrigins(List.of(
                "http://localhost:5500",
                "http://127.0.0.1:5500",
                "http://localhost:5173",
                "http://localhost:8080",
                "http://172.24.64.55:8080"
        ));

        // 允许的HTTP方法
        config.setAllowedMethods(List.of(
                "GET", "POST", "PUT", "DELETE", "OPTIONS"
        ));

        // 允许的头部（必须包含Authorization）
        config.setAllowedHeaders(List.of(
                "Authorization",
                "Content-Type",
                "X-Captcha-Token",
                "Cookie"
        ));

        // 暴露的头部（让前端能获取的响应头）
        config.setExposedHeaders(List.of(
                "Authorization",
                "Set-Cookie",
                "X-New-Access-Token",
                "X-RateLimit-Remaining"
        ));

        // 是否允许凭证（Cookie等）
        config.setAllowCredentials(true);

        // 预检请求缓存时间（秒）
        config.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return source;
    }
}
